package ch.sv7.tool.dbmanager.db.conversion;

import java.io.UnsupportedEncodingException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import ch.sv7.tool.dbmanager.db.ColumnSchema;
import ch.sv7.tool.dbmanager.db.dialect.CustomTypeConversion;
import ch.sv7.tool.log.Logger;

/**
 * Data conversion from type:
 * image (or any binary data)
 * to text or unitext 
 * @author svt
 *
 */
public class UnicodeCustomTypeConversion implements CustomTypeConversion {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(UnicodeCustomTypeConversion.class);

	private String charsetName = "UTF8";
	
	public boolean convertType(ResultSet rs, String columnToRead, PreparedStatement updateStatement, int columnIndexToWrite, ColumnSchema fromColumn, ColumnSchema toColumn)
			throws SQLException {
		String value;
		byte[] bytes = rs.getBytes(columnToRead);
		if (bytes == null) {
			return false;
		}
		try {
			value = new String(bytes, charsetName);
			updateStatement.setString(columnIndexToWrite, value);
			return true;
		} catch (UnsupportedEncodingException e) {
			logger.error(e.getMessage());
			return false;
		}	
	}

	public String getCharsetName() {
		return charsetName;
	}

	public void setCharsetName(String charsetName) {
		this.charsetName = charsetName;
	}
	
	/*
	public String getFromType() {
		return "image";
	}

	public String getToType() {
		return "unitext";
	}
	*/
	
}	
